<template>
  <div class="my-profile">
    <a-spin :spinning="loading">
      <a-card title="个人中心">
        <template #extra>
          <a-space>
            <a-button v-if="!isEditing" type="primary" @click="isEditing = true">编辑资料</a-button>
            <template v-else>
              <a-button @click="handleCancel">取消</a-button>
              <a-button type="primary" @click="handleSave" :loading="saving">保存</a-button>
            </template>
          </a-space>
        </template>

        <!-- 查看模式 -->
        <template v-if="!isEditing">
          <a-descriptions bordered :column="2">
            <a-descriptions-item label="用户名">{{ userInfo.username || '-' }}</a-descriptions-item>
            <a-descriptions-item label="邮箱">{{ userInfo.email || '-' }}</a-descriptions-item>
            <a-descriptions-item label="姓名">
              {{ userInfo.first_name || '' }} {{ userInfo.last_name || '' }}
            </a-descriptions-item>
            <a-descriptions-item label="性别">{{ userInfo.profile?.gender || '-' }}</a-descriptions-item>
            
            <a-descriptions-item label="学号">{{ userInfo.profile?.student_id || '-' }}</a-descriptions-item>
            <a-descriptions-item label="班级">{{ userInfo.profile?.class_name || '-' }}</a-descriptions-item>
            <a-descriptions-item label="专业">{{ userInfo.profile?.major || '-' }}</a-descriptions-item>
            <a-descriptions-item label="手机号">{{ userInfo.profile?.phone || '-' }}</a-descriptions-item>
            
            <a-descriptions-item label="部门">{{ userInfo.profile?.department || '-' }}</a-descriptions-item>
            <a-descriptions-item label="职位">{{ userInfo.profile?.position || '-' }}</a-descriptions-item>
            <a-descriptions-item label="工号">{{ userInfo.profile?.employee_id || '-' }}</a-descriptions-item>
            <a-descriptions-item label="入职日期">{{ userInfo.profile?.hire_date || '-' }}</a-descriptions-item>
            
            <a-descriptions-item label="账号状态">
              <a-tag :color="userInfo.is_active ? 'green' : 'red'">
                {{ userInfo.is_active ? '正常' : '已禁用' }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="管理员权限">
              <a-tag :color="userInfo.is_staff ? 'blue' : 'default'">
                {{ userInfo.is_staff ? '是' : '否' }}
              </a-tag>
            </a-descriptions-item>
            
            <a-descriptions-item label="备注" :span="2">
              {{ userInfo.profile?.remarks || '-' }}
            </a-descriptions-item>
          </a-descriptions>
        </template>

        <!-- 编辑模式 -->
        <template v-else>
          <a-form
            :model="editForm"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="用户名">
                  <a-input v-model:value="editForm.username" disabled />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="邮箱">
                  <a-input v-model:value="editForm.email" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="姓">
                  <a-input v-model:value="editForm.last_name" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="名">
                  <a-input v-model:value="editForm.first_name" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="性别">
                  <a-select v-model:value="editForm.profile.gender" placeholder="请选择性别">
                    <a-select-option value="男">男</a-select-option>
                    <a-select-option value="女">女</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="手机号">
                  <a-input v-model:value="editForm.profile.phone" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="学号">
                  <a-input v-model:value="editForm.profile.student_id" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="班级">
                  <a-input v-model:value="editForm.profile.class_name" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="专业">
                  <a-input v-model:value="editForm.profile.major" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="部门">
                  <a-input v-model:value="editForm.profile.department" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="职位">
                  <a-input v-model:value="editForm.profile.position" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="工号">
                  <a-input v-model:value="editForm.profile.employee_id" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="入职日期">
                  <a-date-picker 
                    v-model:value="editForm.profile.hire_date" 
                    style="width: 100%"
                    format="YYYY-MM-DD"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="24">
                <a-form-item label="备注" :label-col="{ span: 3 }" :wrapper-col="{ span: 20 }">
                  <a-textarea 
                    v-model:value="editForm.profile.remarks" 
                    :rows="4"
                    placeholder="请输入备注信息"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </template>
      </a-card>

      <!-- 修改密码卡片 -->
      <a-card title="修改密码" style="margin-top: 16px">
        <a-form
          :model="passwordForm"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="原密码" required>
                <a-input-password v-model:value="passwordForm.old_password" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="新密码" required>
                <a-input-password v-model:value="passwordForm.new_password" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="确认密码" required>
                <a-input-password v-model:value="passwordForm.confirm_password" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="24">
              <a-form-item :wrapper-col="{ offset: 6, span: 16 }">
                <a-button type="primary" @click="handleChangePassword" :loading="changingPassword">
                  修改密码
                </a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-card>

      <!-- 四六级成绩卡片 -->
      <a-card title="英语四六级成绩" style="margin-top: 16px">
        <a-row :gutter="16">
          <!-- 英语四级 -->
          <a-col :span="12">
            <a-card size="small" title="英语四级" :bordered="false">
              <a-descriptions :column="1" bordered size="small">
                <a-descriptions-item label="成绩">
                  {{ userInfo.profile?.cet4_score || '未提交' }}
                </a-descriptions-item>
                <a-descriptions-item label="状态">
                  <a-tag :color="getCETStatusColor(userInfo.profile?.cet4_status)">
                    {{ userInfo.profile?.cet4_status || '未提交' }}
                  </a-tag>
                </a-descriptions-item>
                <a-descriptions-item 
                  label="拒绝理由" 
                  v-if="userInfo.profile?.cet4_status === '未通过' && userInfo.profile?.cet4_reject_reason"
                >
                  <span style="color: #ff4d4f">{{ userInfo.profile.cet4_reject_reason }}</span>
                </a-descriptions-item>
              </a-descriptions>
              <div style="margin-top: 12px">
                <a-button 
                  v-if="canSubmitCET4" 
                  type="primary" 
                  size="small" 
                  @click="showCETModal('cet4')"
                >
                  {{ userInfo.profile?.cet4_status === '未通过' ? '重新提交' : '提交成绩' }}
                </a-button>
                <a-tag v-else-if="userInfo.profile?.cet4_status === '已通过'" color="success">
                  ✓ 审核已通过
                </a-tag>
                <a-tag v-else-if="userInfo.profile?.cet4_status === '审核中'" color="processing">
                  ⏳ 审核中，请耐心等待
                </a-tag>
              </div>
            </a-card>
          </a-col>

          <!-- 英语六级 -->
          <a-col :span="12">
            <a-card size="small" title="英语六级" :bordered="false">
              <a-descriptions :column="1" bordered size="small">
                <a-descriptions-item label="成绩">
                  {{ userInfo.profile?.cet6_score || '未提交' }}
                </a-descriptions-item>
                <a-descriptions-item label="状态">
                  <a-tag :color="getCETStatusColor(userInfo.profile?.cet6_status)">
                    {{ userInfo.profile?.cet6_status || '未提交' }}
                  </a-tag>
                </a-descriptions-item>
                <a-descriptions-item 
                  label="拒绝理由" 
                  v-if="userInfo.profile?.cet6_status === '未通过' && userInfo.profile?.cet6_reject_reason"
                >
                  <span style="color: #ff4d4f">{{ userInfo.profile.cet6_reject_reason }}</span>
                </a-descriptions-item>
              </a-descriptions>
              <div style="margin-top: 12px">
                <a-button 
                  v-if="canSubmitCET6" 
                  type="primary" 
                  size="small" 
                  @click="showCETModal('cet6')"
                >
                  {{ userInfo.profile?.cet6_status === '未通过' ? '重新提交' : '提交成绩' }}
                </a-button>
                <a-tag v-else-if="userInfo.profile?.cet6_status === '已通过'" color="success">
                  ✓ 审核已通过
                </a-tag>
                <a-tag v-else-if="userInfo.profile?.cet6_status === '审核中'" color="processing">
                  ⏳ 审核中，请耐心等待
                </a-tag>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </a-card>
    </a-spin>

    <!-- 提交成绩弹窗 -->
    <a-modal
      v-model:open="cetModalVisible"
      :title="cetModalTitle"
      @ok="handleSubmitCET"
      :confirmLoading="submittingCET"
      width="600px"
    >
      <a-form :label-col="{ span: 7 }" :wrapper-col="{ span: 15 }">
        <a-form-item label="考试类型">
          <a-input :value="cetModalTitle" disabled />
        </a-form-item>
        
        <a-form-item label="成绩" required>
          <a-input-number
            v-model:value="cetForm.score"
            :min="0"
            :max="710"
            :step="1"
            style="width: 100%"
            placeholder="请输入成绩（0-710）"
          />
        </a-form-item>
        
        <a-form-item label="免修证明图片" required>
          <a-upload
            :file-list="cetForm.exemptionFileList"
            :before-upload="(file: any) => handleBeforeUpload(file, 'exemption')"
            :remove="() => handleRemoveImage('exemption')"
            list-type="picture-card"
            accept="image/*"
            :max-count="1"
          >
            <div v-if="cetForm.exemptionFileList.length < 1">
              <plus-outlined />
              <div style="margin-top: 8px">上传图片</div>
            </div>
          </a-upload>
          <div style="color: #999; font-size: 12px; margin-top: 4px">
            请上传带有姓名的免修证明截图（JPG/PNG，最大5MB）
          </div>
        </a-form-item>
        
        <a-form-item label="成绩证明图片" required>
          <a-upload
            :file-list="cetForm.scoreFileList"
            :before-upload="(file: any) => handleBeforeUpload(file, 'score')"
            :remove="() => handleRemoveImage('score')"
            list-type="picture-card"
            accept="image/*"
            :max-count="1"
          >
            <div v-if="cetForm.scoreFileList.length < 1">
              <plus-outlined />
              <div style="margin-top: 8px">上传图片</div>
            </div>
          </a-upload>
          <div style="color: #999; font-size: 12px; margin-top: 4px">
            请上传带有姓名和分数的成绩证明截图（JPG/PNG，最大5MB）
          </div>
        </a-form-item>
        
        <a-alert
          message="温馨提示"
          description="提交后将进入审核流程，审核通过后成绩将正式生效。请确保成绩和图片真实有效。"
          type="info"
          show-icon
        />
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { authAPI, userAPI, type UserDetail } from '@/api/user'
import { uploadToServer } from '@/utils/cosUpload'
import dayjs, { Dayjs } from 'dayjs'
import type { UploadProps } from 'ant-design-vue'

const loading = ref(false)
const saving = ref(false)
const changingPassword = ref(false)
const isEditing = ref(false)

// 四六级相关
const cetModalVisible = ref(false)
const cetModalTitle = ref('')
const currentCETType = ref<'cet4' | 'cet6'>('cet4')
const submittingCET = ref(false)

const cetForm = reactive({
  score: undefined as number | undefined,
  exemptionFileList: [] as any[],
  scoreFileList: [] as any[],
  exemptionPicUrl: '',
  scorePicUrl: ''
})

const userInfo = ref<UserDetail>({
  id: 0,
  username: '',
  email: '',
  first_name: '',
  last_name: ''
})

const editForm = reactive<any>({
  username: '',
  email: '',
  first_name: '',
  last_name: '',
  profile: {
    student_id: '',
    major: '',
    class_name: '',
    gender: undefined,
    phone: '',
    department: '',
    position: '',
    employee_id: '',
    hire_date: undefined as Dayjs | undefined,
    remarks: ''
  }
})

const passwordForm = reactive({
  old_password: '',
  new_password: '',
  confirm_password: ''
})

// 四六级状态颜色
const getCETStatusColor = (status?: string) => {
  const colorMap: Record<string, string> = {
    '未提交': 'default',
    '审核中': 'processing',
    '已通过': 'success',
    '未通过': 'error'
  }
  return colorMap[status || '未提交'] || 'default'
}

// 是否可以提交四级
const canSubmitCET4 = computed(() => {
  const status = userInfo.value.profile?.cet4_status
  return !status || status === '未提交' || status === '未通过'
})

// 是否可以提交六级
const canSubmitCET6 = computed(() => {
  const status = userInfo.value.profile?.cet6_status
  return !status || status === '未提交' || status === '未通过'
})

// 显示四六级提交弹窗
const showCETModal = (type: 'cet4' | 'cet6') => {
  currentCETType.value = type
  cetModalTitle.value = type === 'cet4' ? '英语四级' : '英语六级'
  cetForm.score = type === 'cet4' 
    ? userInfo.value.profile?.cet4_score 
    : userInfo.value.profile?.cet6_score
  cetForm.exemptionFileList = []
  cetForm.scoreFileList = []
  cetForm.exemptionPicUrl = ''
  cetForm.scorePicUrl = ''
  cetModalVisible.value = true
}

// 图片上传前验证
const handleBeforeUpload = async (file: File, type: 'exemption' | 'score') => {
  // 验证文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件！')
    return false
  }
  
  // 验证文件大小
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    message.error('图片大小不能超过 5MB！')
    return false
  }
  
  // 使用统一的上传工具
  try {
    const result = await uploadToServer(file, 'cet')
    
    if (!result.success) {
      message.error(result.message)
      return false
    }
    
    const url = result.url
    
    if (type === 'exemption') {
      cetForm.exemptionPicUrl = url
      cetForm.exemptionFileList = [{
        uid: '-1',
        name: file.name,
        status: 'done',
        url: url
      }]
    } else {
      cetForm.scorePicUrl = url
      cetForm.scoreFileList = [{
        uid: '-1',
        name: file.name,
        status: 'done',
        url: url
      }]
    }
    
    message.success('上传成功')
  } catch (error: any) {
    message.error('上传失败: ' + (error.message || '未知错误'))
  }
  
  return false // 阻止默认上传行为
}

// 移除图片
const handleRemoveImage = (type: 'exemption' | 'score') => {
  if (type === 'exemption') {
    cetForm.exemptionFileList = []
    cetForm.exemptionPicUrl = ''
  } else {
    cetForm.scoreFileList = []
    cetForm.scorePicUrl = ''
  }
}

// 提交四六级成绩
const handleSubmitCET = async () => {
  if (!cetForm.score) {
    message.error('请输入成绩')
    return
  }
  
  if (cetForm.score < 0 || cetForm.score > 710) {
    message.error('成绩范围应为0-710分')
    return
  }
  
  if (!cetForm.exemptionPicUrl) {
    message.error('请上传免修证明图片')
    return
  }
  
  if (!cetForm.scorePicUrl) {
    message.error('请上传成绩证明图片')
    return
  }
  
  submittingCET.value = true
  try {
    const res = await userAPI.submitCET({
      exam_type: currentCETType.value,
      score: cetForm.score,
      exemption_pic: cetForm.exemptionPicUrl,
      score_pic: cetForm.scorePicUrl
    })
    
    message.success(res.data.message || '提交成功')
    cetModalVisible.value = false
    cetForm.score = undefined
    cetForm.exemptionFileList = []
    cetForm.scoreFileList = []
    cetForm.exemptionPicUrl = ''
    cetForm.scorePicUrl = ''
    
    // 重新加载用户信息
    await loadUserInfo()
  } catch (error: any) {
    message.error('提交失败: ' + (error.response?.data?.message || error.message))
  } finally {
    submittingCET.value = false
  }
}

// 加载当前用户信息
const loadUserInfo = async () => {
  loading.value = true
  try {
    const res = await authAPI.getCurrentUser()
    userInfo.value = res.data
    // 同步到编辑表单
    syncEditForm()
  } catch (error: any) {
    message.error('加载用户信息失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 同步编辑表单
const syncEditForm = () => {
  editForm.username = userInfo.value.username
  editForm.email = userInfo.value.email || ''
  editForm.first_name = userInfo.value.first_name || ''
  editForm.last_name = userInfo.value.last_name || ''
  
  if (userInfo.value.profile) {
    editForm.profile.student_id = userInfo.value.profile.student_id || ''
    editForm.profile.major = userInfo.value.profile.major || ''
    editForm.profile.class_name = userInfo.value.profile.class_name || ''
    editForm.profile.gender = userInfo.value.profile.gender
    editForm.profile.phone = userInfo.value.profile.phone || ''
    editForm.profile.department = userInfo.value.profile.department || ''
    editForm.profile.position = userInfo.value.profile.position || ''
    editForm.profile.employee_id = userInfo.value.profile.employee_id || ''
    editForm.profile.hire_date = userInfo.value.profile.hire_date 
      ? dayjs(userInfo.value.profile.hire_date) 
      : undefined
    editForm.profile.remarks = userInfo.value.profile.remarks || ''
  }
}

// 取消编辑
const handleCancel = () => {
  isEditing.value = false
  syncEditForm() // 恢复原数据
}

// 保存修改
const handleSave = async () => {
  saving.value = true
  try {
    const updateData: any = {
      email: editForm.email,
      first_name: editForm.first_name,
      last_name: editForm.last_name,
      profile: {
        student_id: editForm.profile.student_id,
        major: editForm.profile.major,
        class_name: editForm.profile.class_name,
        gender: editForm.profile.gender,
        phone: editForm.profile.phone,
        department: editForm.profile.department,
        position: editForm.profile.position,
        employee_id: editForm.profile.employee_id,
        hire_date: editForm.profile.hire_date 
          ? editForm.profile.hire_date.format('YYYY-MM-DD') 
          : undefined,
        remarks: editForm.profile.remarks
      }
    }
    
    await userAPI.patchUser(userInfo.value.id, updateData)
    message.success('保存成功')
    isEditing.value = false
    // 重新加载数据
    await loadUserInfo()
    // 更新 localStorage 中的用户信息
    localStorage.setItem('user', JSON.stringify(userInfo.value))
  } catch (error: any) {
    message.error('保存失败: ' + (error.response?.data?.message || error.message))
  } finally {
    saving.value = false
  }
}

// 修改密码
const handleChangePassword = async () => {
  if (!passwordForm.old_password || !passwordForm.new_password || !passwordForm.confirm_password) {
    message.error('请填写完整的密码信息')
    return
  }
  
  if (passwordForm.new_password !== passwordForm.confirm_password) {
    message.error('两次输入的新密码不一致')
    return
  }
  
  if (passwordForm.new_password.length < 6) {
    message.error('新密码长度不能少于6位')
    return
  }
  
  changingPassword.value = true
  try {
    // TODO: 调用修改密码接口（需要后端支持）
    // await userAPI.changePassword({
    //   old_password: passwordForm.old_password,
    //   new_password: passwordForm.new_password
    // })
    
    message.success('密码修改成功，请重新登录')
    
    // 清空表单
    passwordForm.old_password = ''
    passwordForm.new_password = ''
    passwordForm.confirm_password = ''
    
    // TODO: 跳转到登录页
    // setTimeout(() => {
    //   localStorage.removeItem('token')
    //   localStorage.removeItem('user')
    //   window.location.href = '/login'
    // }, 1500)
  } catch (error: any) {
    message.error('密码修改失败: ' + (error.response?.data?.message || error.message))
  } finally {
    changingPassword.value = false
  }
}

onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.my-profile {
  padding: 0;
}
</style>
